package com.htgd.gardenexpo.api;

import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.controller.BasicInformationManagementController;
import com.htgd.gardenexpo.controller.PersonalCenterController;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeBaseUser;
import com.htgd.gardenexpo.entity.SingleUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * @author lihailong
 * @date
 */
@RestController
@RequestMapping("/api/singlePoint")
@Slf4j
@Api(tags = "单点登录API")
public class SinglePointController {
    @Value("${single_point.client_id}")
    public String client_id;

    @Value("${single_point.client_secret}")
    public String client_secret;

    @Value("${single_point.url}")
    public String url;

    @Autowired
    private BasicInformationManagementController basicInformationManagementController;

    @Autowired
    private PersonalCenterController personalCenterController;

    @GetMapping("/login")
    @ApiOperation("授权登录")
    public CommonResult<GeBaseUser> login(String code) {
        CommonResult<GeBaseUser> result = new CommonResult<>();
        JSONObject token = getToken(code);

//        String tokens = "{\n" +
//                "    \"code\": 200,    // 200表示请求成功，非200标识请求失败, 以下不再赘述 \n" +
//                "    \"msg\": \"ok\",\n" +
//                "    \"data\": {\n" +
//                "        \"access_token\": \"7Ngo1Igg6rieWwAmWMe4cxT7j8o46mjyuabuwLETuAoN6JpPzPO2i3PVpEVJ\",     // Access-Token值\n" +
//                "        \"refresh_token\": \"ZMG7QbuCVtCIn1FAJuDbgEjsoXt5Kqzii9zsPeyahAmoir893ARA4rbmeR66\",    // Refresh-Token值\n" +
//                "        \"expires_in\": 7199,                 // Access-Token剩余有效期，单位秒  (两小时)\n" +
//                "        \"refresh_expires_in\": 2591999,      // Refresh-Token剩余有效期，单位秒  (30天)\n" +
//                "        \"client_id\": \"1001\",                // 应用id\n" +
//                "        \"scope\": \"userinfo\",                // 此令牌包含的权限, userinfo:获取用户信息\n" +
//                "        \"openid\": \"gr_SwoIN0MC1ewxHX_vfCW3BothWDZMMtx__\"     // openid \n" +
//                "    }\n" +
//                "}";
//        token = JSONObject.parseObject(tokens);

        if(token.getInteger("code")==200){
            JSONObject data = token.getJSONObject("data");
            String access_token = data.getString("access_token");
            //获取用户信息
            JSONObject user = getUser(access_token);

//            String users = "{\n" +
//                    "    \"code\": 200,\n" +
//                    "    \"msg\": \"ok\",\n" +
//                    "    \"data\": {\n" +
//                    "        \"userName\": \"admin\",\n" +
//                    "        \"nickName\": \"超级管理员\",\n" +
//                    "        \"email\": \"\",\n" +
//                    "        \"phonenumber\": \"15888888888\",\n" +
//                    "        \"sex\": \"1\",\n" +
//                    "        \"avatar\": \"\",\n" +
//                    "        \"openid\": \"3306e771ca3548b2b458df5422f718bc\"\n" +
//                    "    }\n" +
//                    "}";
//            user = JSONObject.parseObject(users);

            if(user.getInteger("code")==200){
                JSONObject data1 = user.getJSONObject("data");
                SingleUser singleUser = data1.toJavaObject(SingleUser.class);
                GeBaseUser geBaseUser = new GeBaseUser();
                geBaseUser.setUsername(singleUser.getNickName());
                geBaseUser.setPassword("123456");
                geBaseUser.setPhone(singleUser.getPhonenumber());
                geBaseUser.setNickname(singleUser.getUserName());
                geBaseUser.setSex(Integer.valueOf(singleUser.getSex()));
                geBaseUser.setAvatar(singleUser.getAvatar());
                geBaseUser.setWxOpenid(singleUser.getOpenid());
                if("admin".equals(singleUser.getUserName())){//管理员
                    geBaseUser.setRoleId("2");
                }else {
                    geBaseUser.setRoleId("37");
                }
                try {
                    basicInformationManagementController.addUserInfo(geBaseUser);
                    String s =  "{\"phone\":\""+geBaseUser.getPhone()+"\",\"password\":\"123456\"}";
                    CommonResult<GeBaseUser> geBaseUserCommonResult = personalCenterController.userLogin(s);
                    return CommonResult.success(geBaseUserCommonResult.getMessage(),geBaseUserCommonResult.getData());
                } catch (InvalidKeySpecException e) {
                    throw new RuntimeException(e);
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException(e);
                }
            }else {
                return CommonResult.error("获取user失败："+user.getString("msg"));
            }
        }else {
            return CommonResult.error("获取token失败："+token.getString("msg"));
        }
    }

    @GetMapping("/getToken")
    @ApiOperation("获取token")
    public JSONObject getToken(String code) {
        // 替换为实际的参数
        String clientId = client_id;
        String clientSecret = client_secret;

        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();

        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建请求体
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type", "authorization_code");
        body.add("client_id", clientId);
        body.add("client_secret", clientSecret);
        body.add("code", code);

        // 创建请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(url+"token", HttpMethod.POST, requestEntity, String.class);

        JSONObject jsonObject = JSONObject.parseObject(response.getBody());

        return jsonObject;
    }

    @GetMapping("/getUser")
    @ApiOperation("根据token获取用户信息")
    public JSONObject getUser(String token) {
        String clientId = client_id;
        String clientSecret = client_secret;

        RestTemplate restTemplate = new RestTemplate();

        // Set up the request parameters
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("client_id", clientId);
        body.add("client_secret", clientSecret);
        body.add("access_token", token);

        // Set up the headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // Create the request entity
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        // Make the POST request
        ResponseEntity<String> response = restTemplate.postForEntity(url+"userinfo", requestEntity, String.class);

        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        return jsonObject;
    }
}
